<template>
  <div id="updateManagerInfo">
    <el-tabs v-model="activeName" class="tabPlane">
      <el-tab-pane label="个人信息" name='1'>
        <div class="goback" @click="routerGoBack">
          <i class="el-icon-arrow-left" style="font-size:14px;vertical-align: middle;"></i>返回 </div>
        <div class="contentClass updateinfoContent">
          <el-form :model="basicInfoForm" status-icon ref="basicInfoForm" :rules="basicInfoFormRules" class="updateForm" label-position="top">
            <el-row :gutter="100">
              <el-col :span='24'>
                <el-form-item label="" prop="picUrl">
                  <div class="clearFix p10">
                    <el-upload
                      class="avatar-uploader"
                      :action="`${isDev ? '/root' : ''}/fastdfs-util/api/fastdfs/upload/image/sample`"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img :src="studentHeader" class="avatar">
                    </el-upload>
                    <p style="font-size:12px;font-weight:300;">点击图片，上传照片，请上传小于5M的照片</p>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <h2 class="titleH">基本信息</h2>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工号" prop="sn">
                  <el-input disabled size="small" type="text" v-model="basicInfoForm.sn" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名" prop="name">
                  <el-input size="small" type="text" v-model="basicInfoForm.name" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-select size='small' v-model="basicInfoForm.gender" value-key='id' @change="selectAfterCancleValtor('gender')">
                    <el-option v-for="item in genderOptions" :key="item.id" :label="item.name" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="民族" prop="nation">
                  <el-select size='small' v-model="basicInfoForm.nation" value-key='id' @change="selectAfterCancleValtor('nation')">
                    <el-option v-for="item in nationsOptions" :key="item.id" :label="item.name" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="政治面貌" prop="politicalStatus">
                  <el-select size='small' v-model="basicInfoForm.politicalStatus" value-key='id' @change="selectAfterCancleValtor('politicalStatus')">
                    <el-option v-for="item in politicOptions" :key="item.id" :label="item.name" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="籍贯" prop="originCode">
                  <el-cascader size="small" separator=' ' :options="originOptions" v-model="basicInfoForm.originCode" @change="selectAfterCancleValtor('originCode')">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="idNumber">
                  <el-input size="small" type="text" v-model="basicInfoForm.idNumber" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="校区" prop="campus">
                  <el-select size='small' v-model="basicInfoForm.campus" value-key='id' @change="selectAfterCancleValtor('campus')">
                    <el-option v-for="item in campusOptions" :key="item.id" :label="item.name" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <h2 class="titleH">本人联系信息</h2>
              </el-col>
              <el-col :span="8">
                <el-form-item label="本人电话" prop="phone">
                  <el-input size="small" type="text" v-model="basicInfoForm.phone" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="email">
                  <el-input size="small" type="text" v-model="basicInfoForm.email" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="微信号" prop="wechat">
                  <el-input size="small" type="text" v-model="basicInfoForm.wechat" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="QQ" prop="qq">
                  <el-input size="small" type="text" v-model="basicInfoForm.qq" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item style="text-align:center;margin-top:30px;">
                  <el-button @click="resetForm('basicInfoForm')" style="width:100px;">取消</el-button>
                  <el-button type="primary" @click="submitForm('basicInfoForm')" style="width:100px;">保存</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import defaultPic from '@/assets/images/defaultPic.png'
import {routerPrevName, _checkIdNum, _checkQQ, _checkMobilePhone, _checkEmail, prodUrl} from '@/tools/utils'
import {common} from '@api/index'
export default {
  name: 'updateManagerInfo',
  data () {
    var nationValitor = function (rule, value, callback) {
      if (value.id === '' || value.id === null || value.id === undefined) {
        callback(new Error('请选择民族'))
      } else {
        callback()
      }
    }
    var campusValitor = function (rule, value, callback) {
      if (value.id === '' || value.id === null || value.id === undefined) {
        callback(new Error('请选择校区'))
      } else {
        callback()
      }
    }
    var politicalStatusValitor = function (rule, value, callback) {
      if (value.id === '' || value.id === null || value.id === undefined) {
        callback(new Error('请选择政治面貌'))
      } else {
        callback()
      }
    }
    var genderValitor = function (rule, value, callback) {
      if (value.id === '' || value.id === null || value.id === undefined) {
        callback(new Error('请选择性别'))
      } else {
        callback()
      }
    }
    return {
      userType: parseInt(this.$store.state.user.type),
      uploadPicUrl: null,
      isDev: process.env.NODE_ENV === 'development',
      activeName: '1',
      input: '111',
      // 性别
      genderOptions: [],
      // 民族
      nationsOptions: [],
      // 籍贯
      originOptions: [],
      // 政治面貌
      politicOptions: [],
      // 校区
      campusOptions: [],
      basicInfoForm: {
        sn: null,
        name: null,
        gender: {
          id: '',
          name: ''
        },
        nation: {
          id: '',
          name: ''
        },
        originCode: [],
        politicalStatus: {
          id: '',
          name: ''
        },
        campus: {
          id: '',
          name: ''
        },
        idNumber: null,
        phone: null,
        email: null,
        wechat: null,
        qq: null,
        picUrl: null
      },
      basicInfoFormRules: {
        name: [{required: true, message: '请填写姓名', trigger: 'blur'}],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'},
          {validator: genderValitor, trigger: 'blur'}
        ],
        nation: [
          {required: true, message: '请选择民族', trigger: 'blur'},
          {validator: nationValitor, trigger: 'blur'}
        ],
        politicalStatus: [
          {required: true, message: '请选择政治面貌', trigger: 'blur'},
          {validator: politicalStatusValitor, trigger: 'blur'}
        ],
        campus: [
          {required: true, message: '请选择校区', trigger: 'blur'},
          {validator: campusValitor, trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请填写手机号', trigger: 'blur'},
          {validator: _checkMobilePhone, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请填写邮箱', trigger: 'blur'},
          {validator: _checkEmail, trigger: 'blur'}
        ],
        originCode: [{required: true, message: '请选择籍贯', trigger: 'blur'}],
        qq: [
          {required: true, message: '请填写qq', trigger: 'blur'},
          {validator: _checkQQ, trigger: 'blur'}
        ],
        idNumber: [
          {required: true, message: '请填写身份证号码', trigger: 'blur'},
          {validator: _checkIdNum, trigger: 'blur'}
        ],
        wechat: [{required: true, message: '请填写微信号', trigger: 'blur'}],
        picUrl: [
          {required: true, message: '请上传头像', trigger: 'blur'}
        ]
      }
    }
  },
  computed: {
    studentHeader () {
      return this.basicInfoForm.picUrl ? `/fastdfs-util/api/fastdfs/download/image?filePath=${this.basicInfoForm.picUrl}` : defaultPic
    }
  },
  created () {
    this.initPage()
  },
  mounted () {

  },
  methods: {
    initPage () {
      this.getManagerInfo()
      this.getNations()
      this.getPolitic()
      this.getCampusList()
      this.getGenderList()
      this.getAllProvinces()
    },
    prodUrl,
    // 获取管理者信息
    getManagerInfo () {
      common()._findPersonalInfoBySn().then(res => {
        if (res.status) {
          Object.assign(this.basicInfoForm, res.data,
            {
              gender: common()._genderType(res.data.gender)
            },
            {
              nation: {id: res.data.nationId, name: res.data.nation}
            },
            {
              politicalStatus: {id: res.data.politicalStatus, name: res.data.politicalStatusName}
            },
            {
              originCode: res.data.originCode ? res.data.originCode.split(':') : []
            },
            {campus: {id: res.data.campusId, name: res.data.campus}}
          )
        }
      })
    },
    // 获取民族列表
    getNations () {
      common()._getNations().then(res => {
        this.nationsOptions = []
        if (res.status) {
          this.nationsOptions.push(...res.data)
        }
      })
    },
    // 获取所有的政治面貌
    getPolitic () {
      common()._getPolitic().then(res => {
        this.politicOptions = []
        if (res.status) {
          this.politicOptions.push(...res.data)
        }
      })
    },
    // 获取籍贯列表
    getAllProvinces () {
      common()._getProvincesAll().then(res => {
        this.originOptions = []
        if (res.status) {
          this.originOptions = res.data
        }
      })
    },
    // 获取性别列表
    getGenderList () {
      this.genderOptions = []
      common()._getGenderList().then(res => {
        this.genderOptions.push(...res)
      })
    },
    // 校区列表
    getCampusList () {
      common()._getCampus().then(res => {
        this.campusOptions = []
        if (res.status) {
          this.campusOptions.push(...res.data)
        }
      })
    },
    // 确认修改
    sureUpdateManagerInfo () {
      let params = {
        'email': this.basicInfoForm.email,
        'gender': this.basicInfoForm.gender.id,
        'idNumber': this.basicInfoForm.idNumber,
        'name': this.basicInfoForm.name,
        'nation': this.basicInfoForm.nation.name,
        'nationId': this.basicInfoForm.nation.id,
        'originCode': this.basicInfoForm.originCode.join(':'),
        'originCodeName': '',
        'phone': this.basicInfoForm.phone,
        'picUrl': this.basicInfoForm.picUrl,
        'politicalStatus': this.basicInfoForm.politicalStatus.id,
        'politicalStatusName': this.basicInfoForm.politicalStatus.name,
        'qq': this.basicInfoForm.qq,
        'campusId': this.basicInfoForm.campus.id,
        'campus': this.basicInfoForm.campus.name,
        'wechat': this.basicInfoForm.wechat
      }
      common()._updateManagerInfo(params).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          // this.getManagerInfo()
          this.$router.back()
        }
      })
    },
    // 返回
    routerGoBack () {
      const routerName = this.userType === 10 ? 2 : this.userType
      this.$router.push({
        name: `${routerPrevName(routerName)}_managerInfo`
      })
    },
    beforeAvatarUpload (file) {
      if ((file.type).indexOf('image/') === -1) {
        this.$message('请上传图片!')
      } else if (file.size / 1024 / 1024 > 5) {
        this.$message('请上传小于5M图片!')
      }
    },
    handleAvatarSuccess (response, file) {
      // this.uploadPicUrl = URL.createObjectURL(file.raw)
      // debugger
      this.basicInfoForm.picUrl = response.filePath
      this.$refs['basicInfoForm'].validateField(['picUrl'])
    },
    // 下来对象change时验证
    selectAfterCancleValtor (key) {
      this.$refs['basicInfoForm'].validateField([key])
    },
    // 取消
    resetForm (formName) {
      this.routerGoBack()
      // this.$refs[formName].resetFields()
    },
    // 保存
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否确认提交此次修改?', '个人信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'warning'
          }).then(() => {
            this.sureUpdateManagerInfo()
          }).catch(err => {
            this.$message.error(err)
          })
        } else {
          this.$confirm('当前还有数据为空，请正确填写所有数据！', '个人信息', {
            cancelButtonText: '返回',
            showConfirmButton: false,
            type: 'warning'
          }).then(() => {

          }).catch(() => {

          })
          return false
        }
      })
    }
  }
}
</script>
